package com.handong.handserialprogram.module.setring;

import android.text.TextUtils;

import com.handong.handserialprogram.constants.HttpConstant;
import com.handong.handserialprogram.model.entities.CriminalEntity;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.status.RingResponse;
import com.handong.handserialprogram.module.base.BasePresenter;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 设置脚环
 * Created by Administrator on 2016/12/21.
 */

public class SetRingPresenter extends BasePresenter<SetRingActivity> implements SetRingContract.Presenter {

    private static final String TAG = SetRingPresenter.class.getSimpleName();

    private SerialPortUtil mSerialPortUtil;
    private Vector<FootRingNewEntity> mRingList=new Vector<>();//过滤后的脚环

    //private boolean mIsSetFootRing = false;
    private boolean mIsFirst = true;

    private List<CriminalEntity> mCriminalEntities;

    public void setPersonEntityList(List<CriminalEntity> mCriminalEntities) {
        this.mCriminalEntities = mCriminalEntities;
    }

    public SetRingPresenter(BaseView view) {
        super(view);
        EventBusUtil.register(this);//EventBus
        mSerialPortUtil = SerialPortUtil.getInstance(mView);
    }

    /**
     * 扫描脚环
     */
    @Override
    public void scanAroundFootRing() {
        mSerialPortUtil.openSerialPortToReadData();
    }

    /**
     * 激活脚环
     */
    public void activateFootRing(String id) {
     FootRingNewEntity entity=   mSerialPortUtil.findEntityFromList(id);
        if (entity.isNormalWork()) {
            AppUtil.showShortToast(this.mView, "脚环已激活");
            return;
        }
        mView.showLoadDialog("脚环激活中...");
        this.mSerialPortUtil.activateFootRing(id);
    }

    public void logoutFootRing(String id) {
        this.mView.showLoadDialog("脚环休眠中...");
        this.mSerialPortUtil.logoutFootRing(id);
    }

    protected void forceExit(String id) {
        FootRingNewEntity entity=   mSerialPortUtil.findEntityFromList(id);
        entity.setNormalWork(false);
    }

    /**
     * 接收
     * @param list
     */
    @Subscribe(priority = 98, threadMode = ThreadMode.MAIN)
    public void receiveFootRing(CopyOnWriteArrayList<FootRingNewEntity> list) {

        /*if (this.mRingList == null) {
            this.mRingList = list;
        }*/


        for (FootRingNewEntity entity:list) {
            if(!entity.isBingding()&&!mRingList.contains(entity)){
                mRingList.add(entity);
            }
        }

          //上面处理了应该不会起作用，暂时保留
         /* for (FootRingNewEntity footRingEntity:list) {
            for (CriminalEntity entity:mCriminalEntities) {
                if(entity.getRingEntity()!=null&&entity.getRingEntity().getRingID().equals(footRingEntity.getRingID())){
                    list.remove(footRingEntity);
                }
            }
        }*/

        if (!mIsFirst) {
            if (mView.isFirstGuide()) {
                for (int i=0;i<mRingList.size();i++) {
                    FootRingNewEntity entity=mRingList.get(i);
                    if (entity.isNormalWork()) {
                        mView.showItemGuide(i);//显示引导
                        break;
                    }
                }

            }
            mView.setFirstGuide(false);
        }
        mIsFirst = false;

        this.mView.showFootRingList(mRingList);
    }

    /**
     * 接收脚环反馈
     * @param response
     */
    @Subscribe(priority = 98, threadMode = ThreadMode.MAIN)
    public void receiveRingResponse(RingResponse response) {
        switch (response.getResponseCode()) {
            case RingResponse.ACTIVATE_ORDER://等待脚环连接
                if (response.isSuccess()) {
                    mView.showLoadDialog("脚环正在连接GPS和网络...");
                } else {
                    mView.activateRingError(response.getRingID());
                }
                break;

            case RingResponse.INIT_2GNET_SUCCESS://激活成功
                if (response.isSuccess()) {
                    mView.activateRingSuccess(mSerialPortUtil.findEntityFromList(response.getRingID()));
                } else {
                    mView.activateRingError(response.getRingID());
                }
                break;

            case RingResponse.LOGOUT_ORDER://退出脚环
                mView.dismissLoadingDialog();
                if (response.isSuccess()) {
                    mView.logoutSuccess();
                } else {
                    mView.logoutFail(response.getRingID());
                }
                break;

            case RingResponse.SIM_ERROR://脚环SIM出错
                mView.simInitError(response.getRingID());
                break;
            default:
                return;
        }
    }


    /**
     * 上传脚环数据
     */
    @Override
    public void uploadBingRingInfo(CriminalEntity entity, String missID) {

        RequestParams params = new RequestParams("visit", "BindEquipment");
        params.put("missionID", missID);
        params.put("personID", entity.getPersonId());
        //todo 上传一对多时的脚环id 目前的一个，一对多时候改接口为多个
        params.put("equipmentID", entity.getRingEntity().getRingID());

        //TODO 要修改一对多
//        String ids = "";
//        for (FootRingNewEntity item : mRingList) {
//            if (item.isMyBingding())
//            {
//                ids+=item.getRingID()+",";
//            }
//        }
//        params.put("equipmentID", ids);

        //if ("犯人".equals(entity.getPersonType())) {
        params.put("equipmentType", "1");
        //} else {
        //params.put("equipmentType", "2");
        //}
        params.put("policePhone", SPUtil.getStringValue(SPUtil.PHONE_NAME));
        params.put("sys_companycode", SPUtil.getStringValue(SPUtil.LOGIN_CODE));

        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                mView.bindPersonInfoFail("服务器无响应");
                JLog.d(TAG, "Upload Result:" + throwable.toString());
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d(TAG, "Upload Result:" + s);
                if (!TextUtils.isEmpty(s.toString())) {
                    try {
                        JSONObject obj = new JSONObject(s);
                        if (obj.getBoolean(HttpConstant.RESPONSE_SUCCESS)) {
                            //mIsSetFootRing = true;
                            mView.bindPersonInfoSuccess();
                        } else {
                            mView.bindPersonInfoFail(obj.getString(HttpConstant.FAIL_REASON));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        mView.bindPersonInfoFail("服务器无响应");
                    }
                } else {
                    mView.bindPersonInfoFail("服务器无响应");
                }
            }
        });
    }

    public boolean isCanExit() {

        /*if (mIsSetFootRing) {
            return true;
        }*/
       /* if (mRingList == null || mRingList.isEmpty()) {
            return true;
        }*/
        //休眠绑定的脚环
      /*  FootRingNewEntity localFootRingNewEntity =  mView.getCriminalEntity().getRingEntity();
        if (localFootRingNewEntity!=null&&localFootRingNewEntity.isNormalWork()) {
            mView.showExitDialog(localFootRingNewEntity.getRingID());
            return false;
        }*/
        return true;
    }

    @Override
    protected void exit() {
        EventBusUtil.unRegister(this);
       /* if (mIsSetFootRing) {
            return;
        }*/
        //this.mSerialPortUtil.closeSerialPort();

        super.exit();
    }
}
